package com.sinodata.bsm.cicp.finder.tomcat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.JmxUtil;

public class TomcatEngine extends Finder {

    private static final Logger logger = Logger.getLogger(TomcatEngine.class);

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String port = (String) params.get("PORT");
        String[] attributeNames = new String[] { "name", "baseDir", "defaultHost" };
        Object attrValues[] = null;
        Object attrValueServerInfo = null;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            ObjectName tomcatEngine = new ObjectName("Catalina:type=Engine");
            attrValues = JmxUtil.getAttribute(connection, tomcatEngine, attributeNames);
            ObjectName tomcatServerInfo = new ObjectName("Catalina:type=Server");
            attrValueServerInfo = connection.getAttribute(tomcatServerInfo, "serverInfo");
            String[] info = new String[8];
            list.add(info);
            info[0] = ip + "_tomcat_";
            info[1] = "TomcatEngine";
            info[2] = "TomcatEngine";
            info[3] = (String) attrValueServerInfo; //版本
            info[4] = (String) attrValues[2]; //默认主机
            info[5] = (String) attrValues[0]; //名称
            info[6] = (String) attrValues[1]; //基路径
            info[7] = port; //端口
            return list;
        } catch (Exception e) {
            logger.error("failed to find taomcat engine", e);
            return null;
        } finally {
            JmxUtil.closeConnector(connector);
        }
    }
}
